//package wmmd.disc.webmaster;

import java.io.*;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.util.Calendar;
import javax.servlet.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class ChronoList2 extends HttpServlet {
    
    //----------------------------------------------------------------------------------------
    /**
     * Called by Rl-2.jsp; chronologically lists recent messages posted after a specified time period
     */
    
    public String setDate(int index) {
        //Function returns the date in yyyy-MM-dd format required by jdbc.
        //Set the starting date as follows:
        //0=last month, 1=last week, 2=last day, 3=last 3 days 2010-04-26 10:00:50 MMMM d, yyyy
        
        Calendar rightnow = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        if (index == 0) {
            rightnow.add(Calendar.MONTH, -1);
        } else if (index == 1) {
            rightnow.add(Calendar.DATE, -7);
        } else if (index == 2) {
            rightnow.add(Calendar.DATE, -1);
        } else if (index == 3) {
            rightnow.add(Calendar.DATE, -3);
        }
        
        return dateFormat.format(rightnow.getTime());
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        //The JSP document passes in which db table to use
        String tablename = request.getParameter("tName");
        
        // Variables for date strings
        SimpleDateFormat fullDate = new SimpleDateFormat("M/dd/yy 'at' hh:mm a");
        int TimeSpan = 0;
        
        //Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        ResultSet rs = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            //Get the index for the starting date:
            if(request.getParameter("RDate")!=null) {
                TimeSpan = 0 + Integer.valueOf(request.getParameter("RDate")).intValue();
            } else {
                //Set the index to list messages posted within the past week
                TimeSpan = 0 + Integer.valueOf(request.getParameter("rdate_default")).intValue();;
            }
            
            // Using setDate to set the start date based on the selected index
            String StartDate = setDate(TimeSpan);
            
            // Writes date to page
            out.println(" <strong>" + StartDate + "</strong></p>");
            out.println("<div style=\"margin-left: 0.5in\">");
            
            // Get all the messages in reverse order -- implying most recent topic first
            String SQL = "SELECT ID,Topic,Name,Date,Subject FROM " + tablename + " WHERE Topic > 0 AND Date >= ? ORDER BY Date Desc";
            rs = con.selectSQL_RS(SQL, new Object[]{StartDate});

            // Display the messages in reverse chronological order
            int NumMessages = 0;

            if(rs != null)
            {
                while(rs.next()) {
                    //Store date, topic as strings, remove the time portion of the date string,
                    //and increment message count
                    String id_string = rs.getString("ID");
                    String topic_string = rs.getString("Topic");
                    String nameStr = rs.getString("Name");
                    Timestamp timeStamp = rs.getTimestamp("Date");
                    String subject_string = rs.getString("Subject");

                    // Format the date and username for the screen
                    String dateStr = fullDate.format(timeStamp);
                    //nameStr = nameStr.substring(0, nameStr.length()-2);

                    // Display the main topic
                    NumMessages = NumMessages + 1;
                    out.println("<h4><a href=\"OneTopic.jsp?RTT=" + topic_string + "\">");
                    out.print(topic_string + ".</a>  <a href=\"displaymessage.jsp?RTID=" + id_string + "\">");
                    out.print(subject_string + "</a> by " + nameStr);
                    out.println(" on " + dateStr + "</strong></h4>");
                }
                rs.close();
            }
            out.println("</div>");
            
            // No messages posted since start date
            if(NumMessages == 0) {
                out.println("<p><em>There have been no Messages Posted since " + StartDate + "</em></p>");
            }
        } catch (SQLException e) {
            out.println("SQLException caught in ChronoList2: " + e.getMessage());
        } finally {
            try {
                if(rs != null) rs.close();
                con.CleanUp();
            } catch (SQLException ignored) {}
        }
    }
}